package cn.tedu.ivos.base.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 切面类:为目标方法进行功能增强的类;
 */


/**
 * @Aspect注解:
 *      1.标识该类为切面类;
 *      2.即为目标方法进行功能增强的类;
 */
@Component
@Aspect
public class LogAspect {
    /**
     * 1.@Before注解:前置通知 - 目标方法调用之前执行;
     */
    @Before("execution(public * cn.tedu.ivos.*.controller..*.*(..))")
    public void beforeMethod(JoinPoint joinPoint){
        /*
            1.joinPoint:连接点参数;
            2.获取目标方法名:joinPoint.getSignature().getName();
            3.获取目标方法参数:joinPoint.getArgs();
         */
        String name = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());

        System.out.println("1前置通知，" + name + "方法执行,参数为: " + args);
    }

    /**
     * 2.AfterReturning注解:返回通知 - 目标方法成功返回之后执行;
     *   注意 returning 参数;
     */
    @AfterReturning(value = "execution(public * cn.tedu.ivos.*.controller..*.*(..))",returning = "r")
    public void afterReturningMethod(JoinPoint joinPoint , Object r){
        String name = joinPoint.getSignature().getName();

        System.out.println("2-返回通知: " + name + "方法结束，结果为: " + r);
    }

    /**
     * 3.@AfterThrowing注解:异常通知，当目标方法抛出异常时,被此方法拦截;
     */
    @AfterThrowing(value = "execution(public * cn.tedu.ivos.*.controller..*.*(..))",throwing = "ex")
    public void afterThrowingMethod(JoinPoint joinPoint , Throwable ex){
        String name = joinPoint.getSignature().getName();
        System.out.println("3-异常通知: " + name + "方法异常，提示消息为: "  + ex.getMessage());

    }

    /**
     * 4.After注解:后置通知，当目标方法彻底结束[正常结束和异常结束]后执行;
     */
    @After(value = "execution(public * cn.tedu.ivos.*.controller..*.*(..))")
    public void afterMethod(JoinPoint joinPoint){
        String name = joinPoint.getSignature().getName();
        System.out.println("4-后置通知:目标方法彻底结束后执行");
    }

    /**
     * 5.Around注解，环绕通知，贯穿于所有阶段;
     *      等价于:
     */
    @Around(value = "execution(public * cn.tedu.ivos.*.controller..*.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint){
        Object result = null;
        try {
            //1.前置通知
            System.out.println("环绕1-前置通知:目标对象方法执行之前");
            //2.目标对象方法的执行
            result = joinPoint.proceed();
            //3.返回通知
            System.out.println("环绕2-返回通知:目标对象方法执行之后");
        } catch (Throwable e) {
            //4.异常通知
            System.out.println("环绕3-异常通知：目标对象方法出现异常");
            throw new RuntimeException(e);
        } finally {
            //5.后置通知
            System.out.println("环绕4-后置通知：目标对象方法执行完毕");
        }
        return result;

    }





}
